<template>
  <div>
    <TopFilter
      ref="topfilter"
      :list="topFilterList"
      :cols="3"
      v-show="isShowTop"
      labelWidth="100"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>

    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :isSelectColumn="isShowSe"
      :onColumnsChange="columns => this.columns = columns"
      :onRowSelectChange="selectChangeHandle"
      :onSyncTableData="tableDataChange"
      columnsRef="potenCus_customer_potenCusManage_index_01"
    >
      <template slot="controls" slot-scope="props">
        <multiuse-button
          size="small"
          type="primary"
          :click="addHandle"
          :auth-list="auths"
          auth-mark="/api/cyxdms.clue/potenCus/insertPotenCus"
        >新增</multiuse-button>
        <multiuse-button
          v-show="!isDistribution && !isTransfer"
          size="small"
          type="primary"
          :click="doDistribution"
          :auth-list="auths"
          auth-mark="/api/cyxdms.clue/clue/clueDistributionMarkete"
        >操作分配</multiuse-button>
        <multiuse-button
          v-show="!isDistribution && !isTransfer"
          size="small"
          type="primary"
          :click="doTransfer"
          :auth-list="auths"
          auth-mark="/api/cyxdms.clue/clue/clueDistributionMarkete/allot"
        >操作转移</multiuse-button>
        <multiuse-button
          v-show="!isDistribution && !isTransfer"
          size="small"
          type="primary"
          :loading="exportLoading"
          :click="exportHandle"
          :auth-list="auths"
          auth-mark="/api/cyxdms.clue/potenCus/exportPotenCusManage"
        >导出</multiuse-button>
        <!-- <el-button size="small" type="primary" :loading="exportLoading" @click="exportHandle">导出</el-button> -->
        <span v-show="isDistribution" :style="{
          'margin-left': '10px'
        }">
          <multiuse-button
            size="small"
            type="primary"
            :click="allotHandle"
            :auth-list="auths"
            auth-mark="/api/cyxdms.clue/clue/clueDistributionMarkete"
          >分配</multiuse-button>
          <multiuse-button
            size="small"
            type="primary"
            :click="quitDistribution"
            :auth-list="auths"
            auth-mark="/api/cyxdms.clue/clue/clueDistributionMarkete"
          >返回</multiuse-button>
        </span>
        <span v-show="isTransfer" :style="{
          'margin-left': '10px'
        }">
          <multiuse-button
            size="small"
            type="primary"
            :click="transferHandle"
            :auth-list="auths"
            auth-mark="/api/cyxdms.clue/clue/clueDistributionMarkete/allot"
          >转移</multiuse-button>
          <multiuse-button
            size="small"
            type="primary"
            :click="quitTransfer"
            :auth-list="auths"
            auth-mark="/api/cyxdms.clue/clue/clueDistributionMarkete/allot"
          >返回</multiuse-button>
        </span>
      </template>
    </FilterTable>
    <Drawer
      :visible.sync="visible"
      :title="dialogTitle"
      width="80%"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <cluesModel
        :type="handleType"
        :rowData="formData"
        @close="closeHandler"
        @fatherClose="fatherClose"
        @changeNAME="changeNAME"
      />
    </Drawer>
    <Drawer
      :visible.sync="visibleDetail"
      :title="dialogTitle"
      width="80%"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <div class="father" v-if="this.dataType==10461001">
        <div class="son">
          <!-- <el-button size="small" type="primary" @click="editClick" :disabled="formDataDetail.intentLevel === 15191007 || formDataDetail.intentLevel === 15191006">编辑</el-button> -->
          <!-- <el-button size="small" type="primary" @click="followClick" :disabled="formDataDetail.intentLevel === 15191007 || formDataDetail.intentLevel === 15191006 || formDataDetail.actionId == null ">跟进</el-button> -->
          <multiuse-button
            size="small"
            type="primary"
            :disabled="formDataDetail.intentLevel === 15191004||formDataDetail.intentLevel === 15191006||formDataDetail.intentLevel === 15191007||formDataDetail.intentLevel === 15191008||formDataDetail.clueStatus!=70001002"
            :click="editClick"
            :auth-list="auths"
            auth-mark="/api/cyxdms.clue/potenCus/updatePotenInfo"
          >编辑</multiuse-button>
          <multiuse-button
            size="small"
            type="primary"
            :disabled="formDataDetail.intentLevel === 15191004||formDataDetail.intentLevel === 15191006||formDataDetail.intentLevel === 15191007||(formDataDetail.intentLevel === 15191008&&formDataDetail.actionId == null)|| formDataDetail.actionId == null"
            :click="followClick"
            :auth-list="auths"
            auth-mark="/api/cyxdms.clue/actioned/updateFollowRecord"
          >跟进</multiuse-button>
          <el-button
            size="small"
            type="primary"
            @click="driveClick"
            :disabled="formData.driveing === true||formDataDetail.intentLevel === 15191004||formDataDetail.intentLevel === 15191006||formDataDetail.intentLevel === 15191007||formDataDetail.clueStatus==70001003||formDataDetail.clueStatus==70001004||formDataDetail.clueStatus==70001013"
          >试驾</el-button>
          <el-button
            size="small"
            type="primary"
            @click="offerClick"
            :disabled="formDataDetail.intentLevel === 15191004||formDataDetail.intentLevel === 15191006||formDataDetail.intentLevel === 15191007||formDataDetail.clueStatus==70001003||formDataDetail.clueStatus==70001004||formDataDetail.clueStatus==70001013"
          >报价</el-button>
          <!-- //cms注意 下单按钮不要 -->
          <!-- <el-button size="small" type="primary" @click="orderClick" :disabled="formDataDetail.intentLevel === 15191004||formDataDetail.intentLevel === 15191006||formDataDetail.intentLevel === 15191007||formDataDetail.clueStatus==70001003||formDataDetail.clueStatus==70001004||formDataDetail.clueStatus==70001013">下单</el-button> -->
        </div>
      </div>
      <div class="father" v-else>
        <div class="son">
          <el-button size="small" type="primary" @click="editClick">编辑</el-button>
        </div>
      </div>
      <Detail ref="Detail" :type="handleType" :rowData="formDataDetail" @close="closeHandler" />
      <div
        :style="{
          position: 'absolute',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'center'
        }"
      >
        <el-button @click="closeDialog">返 回</el-button>
      </div>
    </Drawer>
    <BaseDialog
      :visible.sync="followVisible"
      title="客档跟进"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <followModal
        :type="handleType"
        :rowData="formData"
        @fatherClose="fatherClose"
        @close="closeHandler_follow"
      />
    </BaseDialog>
    <Drawer
      :visible.sync="driveVisible"
      title="试驾登记"
      width="80%"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <driveModal :type="handleType" :rowData="formData" @close="closeHandler_drive" />
    </Drawer>
    <Drawer
      :visible.sync="priceVisible"
      title="创建报价"
      width="80%"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <quotedpriceModal
        :quotedpriceModaltype="handleType"
        :rowData="formData"
        @close="closeHandler_price"
      />
    </Drawer>
    <Drawer
      :visible.sync="orderVisible"
      title="客户订单新增"
      width="80%"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <priceModal :type="handleType" :rowData="formData" @close="closeHandler_order" />
    </Drawer>

    <el-dialog
      :visible.sync="consultVisible"
      title="选择顾问"
      :type="consultHandleType"
      :rowData="consultFormData"
      width="65%"
    >
      <el-checkbox-group v-model="checkNames" @change="handleCheckedNamesChange">
        <el-checkbox
          v-for="(item, index) in consults"
          :label="item"
          :key="index"
          style="width:220px;padding:0 0 15px 20px;"
        >{{ item.text }}</el-checkbox>
      </el-checkbox-group>
      <div :style="{
            marginTop:'10px',
            textAlign: 'center'
          }">
        <el-button @click="consultcloseVisible">取 消</el-button>
        <AjaxButton type="primary" :click="consultHandler">确 定</AjaxButton>
      </div>
    </el-dialog>
    <!-- 转移顾问 -->
    <el-dialog
      :visible.sync="consultVisibleZy"
      title="选择顾问1"
      :type="consultHandleTypeZy"
      :rowData="consultFormDataZy"
      width="65%"
    >
      <el-checkbox-group v-model="checkNamesZy" @change="handleCheckedNamesChangeZy">
        <el-checkbox
          v-for="(item, index) in consultsZy"
          :label="item"
          :key="index"
          style="width:220px;padding:0 0 15px 20px;"
        >{{ item.text }}</el-checkbox>
      </el-checkbox-group>
      <div :style="{
            marginTop:'10px',
            textAlign: 'center'
          }">
        <el-button @click="consultcloseVisibleZy">取 消</el-button>
        <AjaxButton type="primary" :click="consultHandler">确 定</AjaxButton>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryPotenCusManage,
  getPotenCusById,
  getAllModal,
  addNewLeads,
  updateNewLeads,
  queryEmployees,
  getConsultantName,
  saveConsultantName,
  queryClueSourceList,
  getOrgType,
  getDealerArea,
  getAllHeatUp,
  getPotenCusManageExcelList
} from '@/api/potenCus/customer/potenCusManage';
import { getUserInfo } from '@/api/potenCus/customer/exhibition';
import { vehicleConfiguration, vehicleConfigurationNew } from '@/api/retail/salesmanage/confirmcar'; //获取五级菜单
import { dictionary } from '@/utils/dictMixin';
import { authority } from '@/utils/authMixin';
import { formatDates } from '@/utils/validate';
import { getAppId } from '@/assets/js/auth';
// import { getJsonTree } from '@/utils/index';
import { getDataType } from '@/assets/js/auth';
import AjaxButton from '@/components/AjaxButton';
import cluesModel from './cluesModel';
import Detail from './detail';
import followModal from '../customerFollowInfo/tabs/followModal';
import driveModal from '../driveManagement/driveModal';
import quotedpriceModal from '../quotedprice/quotedpriceModal';
import priceModal from '../../../retail/salesmanage/salesordermanage/driveModal';
import Cookies from 'js-cookie';
import { exportExcelFile, formatdateByTime } from '@/utils/index';
export default {
  name: 'PotenCusManage',
  mixins: [dictionary, authority],
  components: {
    cluesModel,
    Detail,
    followModal,
    driveModal,
    quotedpriceModal,
    priceModal
  },
  data() {
    return {
      dataType: getDataType('dataType'),
      roleType: localStorage.getItem('roleType'),
      isShowSe: true,
      isShowTop: false,
      // isShowTop1: false,
      isShowAllot: true,
      topFilterList: this.createTopFilters(),
      fetchParams: {},
      selectedRows: [], //选中列表中的行
      visible: false,
      visibleDetail: false,
      consultVisible: false,
      consultVisibleZy: false,
      followVisible: false,
      driveVisible: false,
      priceVisible: false,
      orderVisible: false,
      formData: {},
      // driveData: {}, //to试驾
      formDataDetail: {}, //明细
      consultFormData: {}, //分配
      consultFormDataZy: {}, //转移
      consultHandleType: '',
      consultHandleTypeZy: '',
      dialogTitle: '',
      fetchApi: queryPotenCusManage,
      columns: this.createTableColumns(),
      handleType: '',
      checkNames: [],
      checkNamesZy: [],
      consults: [],
      consultsZy: [], //转移弹出顾问
      conf: { add: '新建', edit: '编辑', show: '明细' },
      isDistribution: false, // 操作分配(是true/否false)
      isTransfer: false, // 操作转移(是true/否false)
      topFilterlength: null, // topFilter元素长度
      exportLoading: false //导出loading
    };
  },
  created() {
    this.init();
    this.isShowSelect();
    this.getClueTree();
    this.getAllHeatUp();
    // this.getConsultant().then((result) => {
    //   let employeeList = result;
    //   let LIST = []
    //   employeeList.forEach(item=>{
    //     if (LIST.length === 0) {
    //       LIST.push(item)
    //     } else {
    //       LIST.some(x => x.value === item.value) ? '' : LIST.push(item)
    //     }
    //   })
    //   this.topFilterList.find(item=>item.fieldName==='consultants').itemList = LIST;
    //   this.consults = LIST
    // })
    let roleTypeC = this.dataType === 'clue' ? '10061012' : '10061012,10061015';
    this.getConsultant(1, roleTypeC, 202040).then(result => {
      // console.log('顾问列表:' , result);
      this.topFilterList.find(item => item.fieldName === 'consultants').itemList = result;
    });
    // 2020/1/7 分配只有网销顾问可选择
    this.getConsultant(1, 10061012, 202041).then(result => {
      // console.log('顾问列表:' , result);
      this.consults = result;
    });
    //转移 弹出顾问   菜单传递60 使用首页相同的规则
    this.getConsultant(1, this.roleType, 202042).then(result => {
      console.log('顾问列表:', result);
      this.consultsZy = result;
    });
  },
  methods: {
    async init() {
      console.log(this.dataType, Cookies.get('baseNO'), "Cookies.get('baseNO')");
      if (Cookies.get('baseNO')) {
        this.fetchParams.customerNameOrPhone = Cookies.get('baseNO');
        this.topFilterList.find(item => item.fieldName == 'customerNameOrPhone').initialValue = Cookies.get('baseNO');
      }
      //查询六级数据 品牌－＞车系－＞车型－＞配置－＞选装－＞颜色
      vehicleConfigurationNew(0, { isUnlimited: 10041001 })
        .then(res => {
          this.topFilterList.find(item => item.fieldName === 'inteCarType').itemList = res.data;
        })
        .catch(err => {
          // console.log(err)
        });
      // 客档状态处理
      let arr = this.createDictList('7000');
      console.log('arr', arr);
      let newArr = [];
      arr.map(x => {
        if (x.value !== 70001005) {
          newArr.push(x);
        }
      });
      this.topFilterList.find(item => item.fieldName === 'clueStatus').itemList = newArr;
    },
    isShowSelect() {
      if (this.dataType != 10461001) {
        this.isShowSe = false;
        this.isShowTop = false;
        // this.isShowTop1 = true
        this.isShowAllot = false;
      } else {
        this.isShowSe = true;
        this.isShowTop = true;
        // this.isShowTop1 = false
        this.isShowAllot = true;
      }
    },
    // 经销商查询
    createTopFilters() {
      return [
        {
          type: 'INPUT',
          label: '关键字',
          fieldName: 'customerNameOrPhone',
          placeholder: '客户名称/手机号'
        },
        {
          type: 'SELECT',
          label: '是否下发',
          fieldName: 'manufacturerIssue',
          placeholder: '请选择',
          itemList: this.createDictList('1004')
        },
        {
          type: 'RANGE_DATE',
          label: '下发/创建时间',
          fieldName: 'dateStart|dateEnd',
          // dateType:'exactdaterange',
          placeholder: '请选择'
        },
        { type: 'RANGE_INPUT_NUMBER', label: '接触次数', selfCols: 3, fieldName: 'contactNumbers', placeholder: '数字', initialValue: undefined, precision: 0, min: 0 },
        {
          type: 'SELECT',
          label: '线索热度',
          fieldName: 'temperatures',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '意向级别',
          fieldName: 'intentLevels',
          placeholder: '请选择',
          itemList: this.createDictList('1519')
        },
        {
          type: 'INPUT_TREE',
          label: '来源渠道',
          fieldName: 'clueSourceIds',
          defaultExpandAll: true,
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'INPUT_CASCADER',
          label: '意向车型',
          fieldName: 'inteCarType',
          placeholder: '请选择',
          options: { titles: ['品牌', '车系', '车型', '配置', '选装', '颜色'] },
          itemList: []
        },
        {
          type: 'SELECT',
          label: '客户类型',
          fieldName: 'customerTypes',
          placeholder: '请选择',
          itemList: [
            { value: 15231001, text: '个人' },
            { value: 15231003, text: '公司' }
          ]
        },
        {
          type: 'SELECT',
          label: '订金类型',
          fieldName: 'depositType',
          placeholder: '请选择',
          itemList: this.createDictList('8050')
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '所属顾问',
          fieldName: 'consultants',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '线索类型',
          fieldName: 'clueEnterTypes',
          placeholder: '请选择',
          itemList: this.createDictList('7019')
        },
        {
          type: 'SELECT',
          label: '逾期未处理',
          fieldName: 'overTime',
          placeholder: '请选择',
          itemList: this.createDictList('1004')
        },
        {
          type: 'RANGE_DATE',
          label: '最后跟进时间',
          fieldName: 'confirmTimeStart|confirmTimeEnd',
          // dateType:'exactdaterange',
          placeholder: '请选择'
        },
        {
          type: 'MULTIPLE_SELECT',
          label: '客档状态',
          fieldName: 'clueStatus',
          placeholder: '请选择',
          // itemList: this.createDictList('7000')
          itemList: []
        },
        {
          type: 'SELECT',
          label: '线索评级等级',
          fieldName: 'mapClueLevel',
          hidden: getAppId()=='beijing'?false:true,
          placeholder: '请选择',
          itemList: [
            { value: 1, text: '一' },
            { value: 2, text: '二' },
            { value: 3, text: '三' },
            { value: 4, text: '四' },
            { value: 5, text: '五' }
          ]
        }
      ];
    },
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button
                  size="mini"
                  type="text"
                  disabled={
                    (this.dataType == 10461003 && props.row.manufacturerIssue == 10041001) ||
                    props.row.intentLevel == 15191004 ||
                    props.row.intentLevel == 15191006 ||
                    props.row.intentLevel == 15191007 ||
                    props.row.intentLevel == 15191008 ||
                    props.row.clueStatus != 70001002
                      ? true
                      : false
                  }
                  onClick={() => this.editHandle(props.row)}
                  auth-list={this.auths}
                  auth-mark={'/api/cyxdms.clue/potenCus/updatePotenInfo'}
                >
                  编辑
                </multiuse-button>
                <multiuse-button size="mini" type="text" onClick={() => this.showHandle(props.row)}>
                  明细
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '客户编号',
          dataIndex: 'potentialCustomerNo',
          sorter: true,
          filter: true,
          width: 150,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '客户类型',
          dataIndex: 'customerType',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1523'),
          render: props => {
            return <span>{this.createDictText(props.row.customerType, '1523')}</span>;
          }
        },
        {
          title: '线索评级等级',
          dataIndex: 'mapClueLevel',
          hidden:getAppId()=='beijing'?false:true,
          align: 'center',
            render: props => {
             return <el-rate disabled={true} v-model={props.row.mapClueLevel}></el-rate>;
          }
        },
        {
          title: '订金类型',
          dataIndex: 'depositType',
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('8050'),
          render: props => {
            return <span>{this.createDictText(props.row.depositType, '8050')}</span>;
          }
        },
        {
          title: '订金金额',
          dataIndex: 'depositAmount',
          sorter: true,
          filter: true,
          width: 150,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '联系人姓名',
          dataIndex: 'contactName',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '性别',
          dataIndex: 'gender',
          align: 'center',
          sorter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1002'),
          render: props => {
            return <span>{this.createDictText(props.row.gender, '1002')}</span>;
          }
        },
        {
          title: '手机号码',
          dataIndex: 'mobilePhone',
          align: 'center',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '省份',
          dataIndex: 'provinceName',
          align: 'center',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '城市',
          dataIndex: 'cityName',
          align: 'center',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '区域',
          dataIndex: 'areaName',
          align: 'center',
          sorter: true,
          filterType: 'input'
        },
        {
          title: '详细地址',
          dataIndex: 'address',
          sorter: true,
          align: 'center',
          width: 180,
          filterType: 'input'
        },
        {
          title: '线索类型',
          dataIndex: 'clueEnterType',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('7019'),
          render: props => {
            return <span>{this.createDictText(props.row.clueEnterType, '7019')}</span>;
          }
        },
        {
          title: '客档状态',
          dataIndex: 'clueStatus',
          align: 'center',
          sorter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('7000'),
          render: props => {
            return <span>{this.createDictText(props.row.clueStatus, '7000')}</span>;
          }
        },
        {
          title: '来源渠道',
          dataIndex: 'clueSourceName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '来源备注',
          dataIndex: 'sourceRemark',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '来源大类',
        //   dataIndex: 'upClueName',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        // },
        // {
        //   title: '来源细分',
        //   dataIndex: 'clueName',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        // },
        {
          title: '意向品牌',
          dataIndex: 'inteBrandName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '意向车系',
          dataIndex: 'inteCarSeriesName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '意向车型',
          dataIndex: 'inteCarTypeName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '意向配置',
          dataIndex: 'inteYearStyleName',
          sorter: true,
          filter: true,
          width: 250,
          filterType: 'input'
        },
        {
          title: '意向选装',
          dataIndex: 'inteOptionName',
          sorter: true,
          filter: true,
          width: 180,
          filterType: 'input'
        },
        // {
        //   title: '意向颜色',
        //   dataIndex: 'inteColourName',
        //   sorter: true,
        //   filter: true,
        //   width: 180,
        //   filterType: 'input',
        // },
        {
          title: '意向颜色（外饰）',
          dataIndex: 'inteColourName',
          sorter: true,
          filter: true,
          width: 180,
          filterType: 'input'
        },
        {
          title: '意向颜色（内饰）',
          dataIndex: 'interiorName',
          sorter: true,
          filter: true,
          width: 180,
          filterType: 'input'
        },
        {
          title: '线索热度',
          dataIndex: 'temperatureName',
          // dataIndex: 'temperature',
          sorter: true,
          // filter: true,
          align: 'center',
          filterType: 'input'
          // filterItems: this.createDictList('7018'),
          // render: props => {
          //   return <span>{this.createDictText(props.row.temperature, '7018')}</span>;
          // }
        },
        {
          title: '意向级别(初始)',
          dataIndex: 'initailLevel',
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1519'),
          render: props => {
            return <span>{this.createDictText(props.row.initailLevel, '1519')}</span>;
          }
        },
        {
          title: '意向级别(当前)',
          dataIndex: 'intentLevel',
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1519'),
          render: props => {
            return <span>{this.createDictText(props.row.intentLevel, '1519')}</span>;
          }
        },
        {
          title: '接触次数',
          dataIndex: 'contactNumber',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '创建人',
          dataIndex: 'createdByName',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '创建时间',
          dataIndex: 'createdAt',
          width: 150,
          align: 'center',
          render: props => {
            return <span>{formatDates(props.row.createdAt)}</span>;
          }
        },
        {
          title: '分配人',
          dataIndex: 'distributionConsultant',
          align: 'center',
          filterType: 'input'
        },
        {
          title: '是否下发',
          dataIndex: 'manufacturerIssue',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.manufacturerIssue, '1004')}</span>;
          }
        },
        {
          title: '下发时间',
          dataIndex: 'manufacturerIssueDate',
          width: 150,
          align: 'center',
          render: props => {
            return <span>{formatDates(props.row.manufacturerIssueDate)} </span>;
          }
        },
        {
          title: '逾期未处理',
          dataIndex: 'isOverTime',
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1004'),
          render: props => {
            return <span>{this.createDictText(props.row.isOverTime, '1004')}</span>;
          }
        },
        {
          title: '最后跟进时间',
          dataIndex: 'lastFlowTime',
          align: 'center',
          filterType: 'checkbox',
          render: props => {
            return <span>{formatDates(props.row.lastFlowTime)}</span>;
          }
        },
        {
          title: '是否进店',
          dataIndex: 'shop',
          align: 'center',
          filterType: 'input',
          render: props => {
            return <span>{props.row.shop == true ? '是' : '否'}</span>;
          }
        },
        {
          title: '进店类型',
          dataIndex: 'shopTime',
          align: 'center',
          filterType: 'input'
        },
        {
          title: '进店次数',
          dataIndex: 'shopNumber',
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '是否试驾',
          dataIndex: 'testDrive',
          align: 'center',
          filterType: 'input',
          render: props => {
            return <span>{props.row.testDrive == true ? '是' : '否'}</span>;
          }
        },
        {
          title: '是否报价',
          dataIndex: 'isPrice',
          align: 'center',
          filterType: 'input',
          render: props => {
            return <span>{props.row.isPrice == true ? '是' : '否'}</span>;
          }
        },
        {
          title: '所属顾问',
          dataIndex: 'currentConsultantName',
          filter: true,
          align: 'center',
          filterType: 'input'
        },
        {
          title: '线索状态更新时间',
          dataIndex: 'clueStatusUpdatedAt',
          width: 150,
          align: 'center',
          render: props => {
            return <span>{formatDates(props.row.clueStatusUpdatedAt)}</span>;
          }
        },
        {
          title: '备注',
          dataIndex: 'remark',
          filter: true,
          width: 150,
          filterType: 'input'
        },
        {
          title: 'CC清洗备注',
          dataIndex: 'ccInvalidReason',
          align: 'center',
          width: 150,
          filterType: 'input'
        }
      ];
    },
    // 客档来源
    async getClueTree() {
      const res = await queryClueSourceList();
      let treeList = res.data;
      treeList.forEach(el => (el.text = el.clueName));
      treeList.forEach(el => (el.value = el.id));
      treeList.forEach(el => (el.parentId = el.parentId));

      this.topFilterList.find(item => item.fieldName === 'clueSourceIds').itemList = treeList;
    },
    // 客档热度定义
    async getAllHeatUp() {
      const res = await getAllHeatUp({ isValid: 10041001 });
      if (res.resultCode === 200) {
        this.topFilterList.find(item => item.fieldName === 'temperatures').itemList = res.data.map(x => ({ value: x.id, text: x.clueHeatName }));
      }
      // let treeList = res.data
    },
    // async getPotenCusList(id) {
    //   const res = await getPotenCusById(id);
    //   console.log('父id编辑', res);
    //   if (res.resultCode === 200) {
    //     // this.formList[0].itemList = res.data.map(x => ({ value: x.brandId, text: x.brandName }));
    //     // this.formData = res.data;
    //   }
    // },
    consultcloseVisible() {
      this.checkNames = [];
      this.selectedRows = [];
      this.consultVisible = false;
      this.fetchParams = { ...this.fetchParams };
    },
    consultcloseVisibleZy() {
      this.checkNamesZy = [];
      this.selectedRows = [];
      this.consultVisibleZy = false;
      this.fetchParams = { ...this.fetchParams };
    },
    async consultHandler() {
      let { isDistribution, isTransfer } = this;
      // TODO:
      if (isDistribution) {
        // buttonType:1分配，2转移
        await this.saveEmployee(1);
      } else if (!isDistribution && isTransfer) {
        await this.saveEmployee(2);
      }
    },
    selectChangeHandle(rows) {
      // console.log('rows', rows);
      // if (!rows.length) return;
      this.selectedRows = rows;
    },
    tableDataChange(data, isFirst) {
      let { isDistribution, isTransfer } = this;
      // if (isFirst && isDistribution) {
      if (isDistribution) {
        // let disabledSelect = data.filter(row => row.clueStatus != 70001001)
        this.$refs.table.$refs.pageTable.SET_DISABLE_SELECT([]);
        // } else if (isFirst && isTransfer) {
      } else if (isTransfer) {
        // let disabledSelect = data.filter(row => row.clueStatus == 70001001)
        this.$refs.table.$refs.pageTable.SET_DISABLE_SELECT([]);
      } else {
        this.$refs.table.$refs.pageTable.SET_DISABLE_SELECT(data);
      }
    },
    addHandle() {
      this.handleType = 'add';
      this.showHandler();
    },
    // 操作分配
    doDistribution() {
      this.isDistribution = true;
      // this.$refs.table.$refs.pageTable.syncTableList(true)
      this.fetchParams = { ...this.fetchParams, allot: 1 };
      this.toggleBtnStatus(true);
    },
    // 取消操作分配
    quitDistribution() {
      let { topFilterlength } = this;
      this.isDistribution = false;
      // this.$refs.table.$refs.pageTable.syncTableList(true)
      // 清除所选
      this.$refs.table.$refs.pageTable.clearSelectionHandle();
      this.fetchParams = { ...this.fetchParams, allot: 2 };
      this.toggleBtnStatus(false);
    },
    // 分配
    allotHandle(row) {
      this.checkNames = [];
      console.log('分配选择行', this.selectedRows);
      if (!this.selectedRows.length) {
        this.$message.info('请先选择');
      } else {
        this.consultVisible = true;
      }
    },
    // 操作转移
    doTransfer() {
      this.isTransfer = true;
      this.$refs.table.$refs.pageTable.syncTableList(true);
      this.fetchParams = { ...this.fetchParams, allot: 4 };
      this.toggleBtnStatus(true);
    },
    // 转移
    transferHandle() {
      this.checkNames = [];
      console.log('转移选择行', this.selectedRows);
      if (!this.selectedRows.length) {
        this.$message.info('请先选择');
      } else {
        this.consultVisibleZy = true;
      }
    },
    // 取消转移
    quitTransfer() {
      this.isTransfer = false;
      this.$refs.table.$refs.pageTable.syncTableList(true);
      // 清除所选
      this.$refs.table.$refs.pageTable.clearSelectionHandle();
      this.fetchParams = { ...this.fetchParams, allot: 2 };
      this.toggleBtnStatus(false);
    },
    // 操作分配、转移，禁用、启用按钮
    toggleBtnStatus(flag) {
      let { topFilterlength } = this;
      if (flag) {
        // 禁用按钮
        this.$refs.topfilter.$el.children[0][topFilterlength - 3].disabled = true;
        this.$refs.topfilter.$el.children[0][topFilterlength - 2].disabled = true;
        this.$refs.topfilter.$el.children[0][topFilterlength - 3].classList.add('is-disabled');
        this.$refs.topfilter.$el.children[0][topFilterlength - 2].classList.add('is-disabled');
      } else {
        // 启用按钮
        this.$refs.topfilter.$el.children[0][topFilterlength - 3].disabled = false;
        this.$refs.topfilter.$el.children[0][topFilterlength - 2].disabled = false;
        this.$refs.topfilter.$el.children[0][topFilterlength - 3].classList.remove('is-disabled');
        this.$refs.topfilter.$el.children[0][topFilterlength - 2].classList.remove('is-disabled');
      }
    },
    // 选择顾问 分配
    handleCheckedNamesChange(value) {
      console.log('当前所选:', value);
      this.checkNames = value;
    },
    // 选择顾问 转移
    handleCheckedNamesChangeZy(value) {
      console.log('当前所选:', value);
      this.checkNamesZy = value;
    },
    async saveEmployee(buttonType) {
      console.log('选中行', this.selectedRows);
      console.log('选中顾问', this.checkNames);

      let userIds = [];
      let orgIds = [];
      if (buttonType == 1) {
        this.checkNames.forEach(x => {
          userIds.push(x.value);
          orgIds.push(x.orgId);
        });
      } else {
        this.checkNamesZy.forEach(x => {
          userIds.push(x.value);
          orgIds.push(x.orgId);
        });
      }

      let data = {
        clueRecordIdDTOList: this.selectedRows,
        userIds: userIds.toString(),
        orgIds: orgIds.toString(),
        buttonType: buttonType
      };
      const res = await saveConsultantName(data);
      console.log('保存顾问', res);
      debugger
      if (res.resultCode === 200) {
        this.$message.success('保存成功!');
      }else{
        this.$message.success(res.errMsg);
      }
       if (buttonType == 1) {
          this.consultcloseVisible();
        } else {
          this.consultcloseVisibleZy();
        }
    },
    editHandle(row) {
      console.log('编辑row', row);
      this.handleType = 'edit';
      this.formData = row;
      this.showHandler();
    },
    async showHandle(row) {
      // TODO:
      const res = await getPotenCusById(row.customerBusinessId, row.clueType);
      this.handleType = 'show';
      this.formDataDetail = res.data;
      let newRow;
      newRow = {
        ...res.data,
        potentialCustomerName: row.customerName,
        potentialCustomerPhone: row.mobilePhone,
        mobile: row.mobilePhone,
        employeeName: row.currentConsultantName,
        customerNo: res.data.customerBusinessId,
        // potentialCustomersId: res.data.customerBusinessId,
        potentialCustomerNo: row.potentialCustomerNo,
        consultant: res.consultant,
        consultantName: res.consultantName,
        // actionId: res.data.clueRecordId,
        driverCard: res.data.certificateNo,
        planActionDate: res.data.planActionDate,
        vehicleUse: res.data['buyCarUse'],
        clueStatus: res.data.clueStatus,
        ccInvalidReason: row.ccInvalidReason,
        driveType: 20261002, //默认试驾
        clueType: 70241002 // 后台确定写死
      };
      this.formData = newRow;
      console.log(this.formData, '跳转携带formData');
      this.showHandlerDetail();
    },
    showHandler() {
      this.dialogTitle = `${this.conf[this.handleType]}客档`;
      this.visible = true;
    },
    showHandlerDetail() {
      this.dialogTitle = `客档${this.conf[this.handleType]}`;
      this.visibleDetail = true;
    },
    // 明细编辑
    editClick() {
      this.handleType = 'edit';
      this.dialogTitle = '客档管理编辑';
      this.visibleDetail = false;
      this.visible = true;
    },
    // 明细跟进
    followClick() {
      this.handleType = 'edit';
      // this.visibleDetail = false;
      this.followVisible = true;
    },
    // 明细试驾
    driveClick() {
      this.handleType = 'add';
      // this.visibleDetail = false;
      // this.driveData = JSON.parse(JSON.stringify(this.formData))
      // this.driveData['customerNo'] = this.driveData['potentialCustomersId']
      this.driveVisible = true;
    },
    // 明细报价
    offerClick() {
      this.handleType = 'add';
      // this.visibleDetail = false;
      this.priceVisible = true;
    },
    // 明细下单  //cms注意  不要
    // orderClick(){
    //   this.handleType = 'add';
    //   // this.visibleDetail = false;
    //   this.orderVisible = true;
    // },
    changeHandle(val) {
      if (val.contactNumbers != null) {
        val.startContactNumber = val.contactNumbers[0];
        val.endContactNumber = val.contactNumbers[1];
      }
      if (isNaN(val.startContactNumber)) val.startContactNumber = undefined;
      if (isNaN(val.endContactNumber)) val.endContactNumber = undefined;
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeHandler_follow(val, type) {
      this.followVisible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
        this.$refs.Detail.tabRefresh();
      }
    },
    closeHandler_drive(val, type) {
      this.driveVisible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler_price(val, type) {
      this.priceVisible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler_order(val, type) {
      this.orderVisible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeDialog() {
      this.visibleDetail = false;
    },
    fatherClose(val, type) {
      console.log('andFollow来的', val);
      this.visible = false;
      this.formData = val.data;
      this.followVisible = true;
      this.closeDialog();
      if (type == '明细跟进') {
        this.handleType = 'edit';
        this.showHandler();
      }
    },
    changeNAME(val, type) {
      console.log('你是不是新来的', val, type);
      this.dialogTitle = '客档管理编辑';
    },
    //客档管理导出
    async exportHandle() {
      let r = await this.$refs.topfilter.GET_FORM_DATA();
      let p = null;
      if (r != null && r.length > 1) {
        p = r[1];
      }
      this.exportLoading = true;
      getPotenCusManageExcelList(p).then(res => {
        exportExcelFile(res.data, '客档管理');
        this.exportLoading = false;
      });
    }
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
    this.topFilterlength = this.$refs.topfilter.$el.children[0].length;
    // 首页进入时
    if (this.$route.query.clueStatus === 70001001) {
      this.fetchParams.clueStatus = this.$route.query.clueStatus;
      this.topFilterList.find(item => item.fieldName === 'clueStatus').initialValue = this.$route.query.clueStatus;
    }
  },
  deactivated() {
    Cookies.set('baseNO', '');
  },
  destroyed() {
    Cookies.set('baseNO', '');
  }
};
</script>

<style lang="less" scoped>
.father {
  width: 380px;
  height: auto;
  position: relative;
  float: right;
}
.son {
  position: absolute;
  // top: -5px;
  right: 10px;
  z-index: 2;
}
</style>
